package C2DMRelated;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class C2DMMessage 
{
	
	//***************************************Class Variables*******************************************//

	public static String MESSAGE_WAITING = new String("message_waiting");
	
	private String _Type = null;
	private Map<String, String> _parameters;


	//***************************************Constructors*******************************************//


	public C2DMMessage(String Type, Map<String, String> parameters)
	{
		this._Type = Type;
		this._parameters = parameters;
	}


	public C2DMMessage(String existing_c2dm_string)
	{
		this._parameters = new HashMap<String, String>();

		int end_of_Type = existing_c2dm_string.indexOf("&");
		this._Type = existing_c2dm_string.substring(0, end_of_Type);

		//now we will execute the parameters into the HashMap - if there are
		int lengthOfMessage = existing_c2dm_string.length();
		if(lengthOfMessage != end_of_Type + 1)
		{
			String stringOfParams = existing_c2dm_string.substring(end_of_Type + 1, lengthOfMessage);
			executeParams(stringOfParams); 
		}
	}


	//***************************************Public Methods*******************************************//


	public String getParamValue(String key)
	{
		return this._parameters.get(key);
	}


	public Set<String> getKeys()
	{
		return this._parameters.keySet();
	}


	public Collection<String> getValue()
	{
		return this._parameters.values();
	}


	public String getType()
	{
		return this._Type;
	}


	public String toString()
	{
		StringBuilder strBuilder = new StringBuilder(1024);

		//printing type
		strBuilder.append(this._Type);

		for (Iterator<String> iterator = this._parameters.keySet().iterator(); iterator.hasNext();) 
		{
			String key = (String) iterator.next();
			strBuilder.append("&" + key + "=" + this._parameters.get(key));
		}

		return strBuilder.toString();
	}


	//***************************************Private Methods*******************************************//

	private void executeParams(String stringOfParams) 
	{
		int end_of_param_name = stringOfParams.indexOf("=");
		int end_of_param_value = stringOfParams.indexOf("&");
		if(end_of_param_value == -1)
		{
			end_of_param_value = stringOfParams.length();
		}
		String param_name = stringOfParams.substring(0, end_of_param_name);
		String param_value = stringOfParams.substring(end_of_param_name + 1, end_of_param_value);
		this._parameters.put(param_name, param_value);

		int lengthOfParam = stringOfParams.length();
		//there are more params to execute
		if(lengthOfParam >= end_of_param_value + 1)
		{
			String restOfParams = stringOfParams.substring(end_of_param_value + 1, lengthOfParam);
			executeParams(restOfParams);
		}
	}
}
